import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _isEmpty from "lodash/isEmpty";

/**
 * index - 角色管理 - 分配权限
 * @date: 2018-10-26

 */
import React, { PureComponent } from 'react';
import { Button, Checkbox, Form, Input, Table, Tag, Row, Col } from 'antd';
import intl from 'utils/intl';
import { tableScrollWidth } from 'utils/utils';
import { SEARCH_FORM_ITEM_LAYOUT } from 'utils/constants';
import Drawer from "../Drawer";
import styles from "./index.less?modules"; // 折叠面板组件初始化

var FormItem = Form.Item;

var PermissionsQueryForm = function PermissionsQueryForm(_ref) {
  var _ref$form = _ref.form,
      form = _ref$form === void 0 ? {} : _ref$form,
      _ref$search = _ref.search,
      search = _ref$search === void 0 ? function (e) {
    return e;
  } : _ref$search;
  var _form$getFieldDecorat = form.getFieldDecorator,
      getFieldDecorator = _form$getFieldDecorat === void 0 ? function (e) {
    return e;
  } : _form$getFieldDecorat,
      _form$resetFields = form.resetFields,
      resetFields = _form$resetFields === void 0 ? function (e) {
    return e;
  } : _form$resetFields;
  return /*#__PURE__*/React.createElement(Form, null, /*#__PURE__*/React.createElement(Row, {
    type: "flex",
    gutter: 24,
    align: "bottom"
  }, /*#__PURE__*/React.createElement(Col, {
    span: 12
  }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, SEARCH_FORM_ITEM_LAYOUT, {
    label: intl.get("ciam.roleManagement.model.roleManagement.permissionSetName").d('权限层级名称')
  }), getFieldDecorator('name')( /*#__PURE__*/React.createElement(Input, null)))), /*#__PURE__*/React.createElement(Col, {
    span: 12
  }, /*#__PURE__*/React.createElement(FormItem, SEARCH_FORM_ITEM_LAYOUT, /*#__PURE__*/React.createElement(Button, {
    onClick: function onClick() {
      return resetFields();
    },
    style: {
      marginRight: '8px'
    }
  }, intl.get("cpaas.common.button.reset").d('重置')), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    htmlType: "submit",
    onClick: function onClick() {
      search();
    }
  }, intl.get("cpaas.common.button.search").d('查询'))))));
};

var WrapperPermissionsQueryForm = Form.create({
  fieldNameProp: null
})(PermissionsQueryForm);

var Permissions = /*#__PURE__*/function (_PureComponent) {
  _inherits(Permissions, _PureComponent);

  var _super = _createSuper(Permissions);

  function Permissions(props) {
    var _this;

    _classCallCheck(this, Permissions);

    _this = _super.call(this, props); // 方法注册

    _this.state = {
      dataSource: [],
      expandedRowKeys: [],
      defaultExpandedRowKeys: []
    };
    _this.defaultTableRowKey = 'id';
    ['handleFetchDataSource', 'handleClose', 'operationRender', 'onExpand', 'collapseAll', 'expandAll'].forEach(function (method) {
      _this[method] = _this[method].bind(_assertThisInitialized(_this));
    });
    _this.searchFormRef = React.createRef();
    return _this;
  }

  _createClass(Permissions, [{
    key: "getSnapshotBeforeUpdate",
    value: function getSnapshotBeforeUpdate(prevProps) {
      var _this$props = this.props,
          visible = _this$props.visible,
          roleId = _this$props.roleId;
      return visible && roleId !== prevProps.roleId;
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState, snapshot) {
      if (snapshot) {
        this.handleFetchDataSource();
      }
    }
  }, {
    key: "handleFetchDataSource",
    value: function handleFetchDataSource() {
      var _this2 = this;

      var _this$props2 = this.props,
          _this$props2$fetchDat = _this$props2.fetchDataSource,
          fetchDataSource = _this$props2$fetchDat === void 0 ? function (e) {
        return e;
      } : _this$props2$fetchDat,
          roleId = _this$props2.roleId;
      var params = {};

      if (this.searchFormRef.current) {
        // because of wrappedComponentRef doesn't get ref, so use ref directly
        params = this.searchFormRef.current.getFieldsValue();
      }

      fetchDataSource(roleId, params).then(function (res) {
        if (res) {
          var _res$dataSource = res.dataSource,
              dataSource = _res$dataSource === void 0 ? [] : _res$dataSource,
              _res$defaultExpandedR = res.defaultExpandedRowKeys,
              defaultExpandedRowKeys = _res$defaultExpandedR === void 0 ? [] : _res$defaultExpandedR;

          _this2.setState({
            dataSource: dataSource,
            defaultExpandedRowKeys: defaultExpandedRowKeys
          });
        }
      });
    }
  }, {
    key: "handleClose",
    value: function handleClose() {
      var _this$props$close = this.props.close,
          close = _this$props$close === void 0 ? function (e) {
        return e;
      } : _this$props$close;
      this.setState({
        dataSource: [],
        expandedRowKeys: []
      });
      close();
    }
  }, {
    key: "onCheckboxChange",
    value: function onCheckboxChange(record) {
      var _this$props3 = this.props,
          _this$props3$batchAss = _this$props3.batchAssignPermissionSets,
          batchAssignPermissionSets = _this$props3$batchAss === void 0 ? function (e) {
        return e;
      } : _this$props3$batchAss,
          _this$props3$batchUna = _this$props3.batchUnassignPermissionSets,
          batchUnassignPermissionSets = _this$props3$batchUna === void 0 ? function (e) {
        return e;
      } : _this$props3$batchUna,
          roleId = _this$props3.roleId;
      var setIdList = [];

      var getSubSetIdList = function getSubSetIdList() {
        var collections = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        // collections.forEach(n => {
        //   if (n.psLeafFlag === 1) {
        //     setIdList.push(n.id);
        //   }
        //   if (!isEmpty(n.subMenus)) {
        //     getSubSetIdList(n.subMenus);
        //   }
        // });
        collections.forEach(function (n) {
          if (n.type === 'ps') {
            setIdList.push(n.id);
          }

          if (!_isEmpty(n.subMenus)) {
            getSubSetIdList(n.subMenus);
          }
        });
      };

      if (record.type === 'ps') {
        setIdList.push(record.id);
      }

      if (!_isEmpty(record.subMenus)) {
        getSubSetIdList(record.subMenus);
      }

      if (record.checkedFlag !== 'Y') {
        batchAssignPermissionSets(roleId, setIdList, this.handleFetchDataSource);
      } else {
        batchUnassignPermissionSets(roleId, setIdList, this.handleFetchDataSource);
      }
    }
    /**
     * expandAll - 全部展开
     */

  }, {
    key: "expandAll",
    value: function expandAll() {
      var defaultExpandedRowKeys = this.state.defaultExpandedRowKeys;
      this.setState({
        expandedRowKeys: defaultExpandedRowKeys
      });
    }
    /**
     * expandAll - 全部收起
     */

  }, {
    key: "collapseAll",
    value: function collapseAll() {
      this.setState({
        expandedRowKeys: []
      });
    }
    /**
     * onExpand - 展开树
     * @param {boolean} expanded - 是否展开
     * @param {record} record - 当前行数据
     */

  }, {
    key: "onExpand",
    value: function onExpand(expanded, record) {
      var _this$state$expandedR = this.state.expandedRowKeys,
          expandedRowKeys = _this$state$expandedR === void 0 ? [] : _this$state$expandedR;
      this.setState({
        expandedRowKeys: expanded ? expandedRowKeys.concat(record.key) : expandedRowKeys.filter(function (o) {
          return o !== record.key;
        })
      });
    }
  }, {
    key: "operationRender",
    value: function operationRender(text, record) {
      var checkboxProps = {
        indeterminate: record.checkedFlag === 'P',
        checked: record.checkedFlag === 'Y',
        onChange: this.onCheckboxChange.bind(this, record)
      }; // if (record.psLeafFlag !== 1) {
      //   checkboxProps.disabled = true;
      // }

      return /*#__PURE__*/React.createElement(Checkbox, checkboxProps);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          _this$props4$prompt = _this$props4.prompt,
          prompt = _this$props4$prompt === void 0 ? {} : _this$props4$prompt,
          roleName = _this$props4.roleName,
          visible = _this$props4.visible,
          _this$props4$processi = _this$props4.processing,
          processing = _this$props4$processi === void 0 ? {} : _this$props4$processi;
      var _this$state = this.state,
          _this$state$dataSourc = _this$state.dataSource,
          dataSource = _this$state$dataSourc === void 0 ? [] : _this$state$dataSourc,
          _this$state$expandedR2 = _this$state.expandedRowKeys,
          expandedRowKeys = _this$state$expandedR2 === void 0 ? [] : _this$state$expandedR2;
      var drawerProps = {
        title: intl.get('ciam.roleManagement.view.title.assign', {
          name: roleName
        }).d("\u7ED9\u201C".concat(roleName, "\u201D\u5206\u914D\u6743\u9650")),
        visible: visible,
        onCancel: this.handleClose,
        width: 620,
        anchor: 'right',
        wrapClassName: styles['ciam-role-permissions-editor'],
        footer: /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          onClick: this.handleClose
        }, intl.get("cpaas.common.button.close").d('关闭'))
      };
      var columns = [// {
      //   title: '编码',
      //   dataIndex: 'code',
      //   width: 300,
      // },
      {
        title: intl.get("ciam.roleManagement.model.roleManagement.permissionSetName").d('权限层级名称'),
        dataIndex: 'name'
      }, {
        title: intl.get("ciam.roleManagement.model.roleManagement.permission.Type").d('权限类型'),
        dataIndex: 'permissionType',
        width: 150,
        render: function render() {
          var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
          var record = arguments.length > 1 ? arguments[1] : undefined;
          var texts = {
            api: intl.get('ciam.roleManagement.view.message.api').d('API'),
            button: intl.get('ciam.roleManagement.view.message.button').d('按钮'),
            table: intl.get('ciam.roleManagement.view.message.table').d('表格列'),
            formItem: intl.get('ciam.roleManagement.view.message.formItem').d('表单项'),
            formField: intl.get('ciam.roleManagement.view.message.formField').d('表单域')
          };
          var valueList = value.split(',') || [];
          var text = valueList.map(function (item) {
            return texts[item] ? texts[item] : '';
          }) || [];
          return record.type === 'ps' && /*#__PURE__*/React.createElement(Tag, {
            color: value === 'api' ? 'green' : 'orange'
          }, text.join());
        }
      }, {
        title: intl.get('cpaas.common.button.action').d('操作'),
        width: 85,
        render: this.operationRender // (text, record) =>
        //   record.psLeafFlag === 1 && (
        //     <Checkbox
        //       indeterminate={record.checkedFlag === 'P'}
        //       checked={record.checkedFlag === 'Y'}
        //       onChange={this.onCheckboxChange.bind(this, record)}
        //     />
        //   ),

      }];
      var tableProps = {
        columns: columns,
        dataSource: dataSource,
        scroll: {
          x: tableScrollWidth(columns, 300)
        },
        loading: processing.query || processing.batchAssignPermissionSets || processing.batchUnassignPermissionSets,
        bordered: true,
        childrenColumnName: 'subMenus',
        pagination: false,
        expandedRowKeys: expandedRowKeys,
        onExpand: this.onExpand
      };
      return /*#__PURE__*/React.createElement(Drawer, drawerProps, /*#__PURE__*/React.createElement(WrapperPermissionsQueryForm, {
        ref: this.searchFormRef,
        search: this.handleFetchDataSource,
        prompt: prompt
      }), /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement("div", {
        className: "action",
        style: {
          textAlign: 'right'
        }
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.collapseAll,
        style: {
          marginRight: 8
        }
      }, intl.get("cpaas.common.button.collapseAll").d('全部收起')), /*#__PURE__*/React.createElement(Button, {
        onClick: this.expandAll
      }, intl.get("cpaas.common.button.expandAll").d('全部展开'))), /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement(Table, tableProps));
    }
  }]);

  return Permissions;
}(PureComponent);

export { Permissions as default };